//
// Created by klen on 23-12-4.
//


#include "file.h"

tuple<vector<directory_entry>, string> GetFileList(const path& findPath) {
    directory_entry entry{findPath};
    if (!exists(findPath)) {
        return {{}, {"该路径不存在"}};
    }
    if (entry.status().type() != file_type::directory) {
        return {{}, {"该路径不是文件夹"}};
    }

    vector<directory_entry> files{};
    directory_iterator iterator{findPath};
    for (const directory_entry& file : iterator) {
        files.push_back(file);
    }

    return {files, {""}};
}

bool ContentSearchText(const string& filename,const string& text) {
    unsigned long idx = filename.find(text, 0);
    if (idx != string::npos) {
        return true;
    }
    return false;
}

tuple<vector<directory_entry>, string> SearchFile(const path& startPos, const string& target ) {
    if (!exists(startPos)) {
        return {{}, {"搜索目录不存在"}};
    } else if (directory_entry{startPos}.status().type() != file_type::directory ) {
        return {{}, {"搜索地址不是一个目录"} };
    }

    vector<directory_entry> findTarget{};
    directory_iterator iterator{startPos};

    for (const directory_entry& file : iterator) {

        if (file.status().type() == file_type::directory) {
            auto [childDirTargets, err] = SearchFile(file, target);
            if (!err.empty()) {
                return {{}, {err}};
            }
            for (const directory_entry& childDirFile: childDirTargets) {
                findTarget.emplace_back(childDirFile);
            }
        } else if (ContentSearchText(file.path().filename(), target)) {
            findTarget.push_back(file);
        }

    }

    return {findTarget, ""};
}